﻿using Google.Protobuf;
using Harmontronics.Api.Config;
using Harmontronics.IService;
using Harmontronics.Model.Dto.Login;
using Harmontronics.Model.Dto.User;
using Harmontronics.Model.Entitys;
using Harmontronics.Model.Other;
using Harmontronics.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Harmontronics.Model.Dto.Role;
using Microsoft.IdentityModel.Tokens;

namespace Harmontronics.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    // [Authorize]
    public class UsersController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IRoleService _roleService;


        public UsersController(IUserService Users, IRoleService roleService)
        {
            _userService = Users;
            _roleService = roleService;
        }


        [HttpPost]
        public ApiResponseData GetUserData(UserGet getData)
        {
          
            List<UserReq> users = _userService.GetUsersList();
            if (getData.employeeNumber.Length > 0)
            {
                // users = users.Where(i => i.EmployeeNumber == getData.employeeNumber).ToList();
                users = users.Where(i => i.EmployeeNumber.Contains(getData.employeeNumber)).ToList();
            }
            if (getData.userName.Length > 0)
            {
                users = users.Where(i => i.UserName.Contains(getData.userName)).ToList();
            }
            int start = (getData.page - 1) * getData.size;
            int end = ((start + getData.size) >= (users.Count)) ? (users.Count) : (start + getData.size);
            List<UserReq> showUsers = users.GetRange(start, end - start);
            return ResultHelper.Success(new ReturnData() { total = users.Count, dataList = showUsers });
        }

        [HttpPost]
        public ApiResponseData AddUser(UserAdd req)
        {
            //验证工号是否重复
            if (!string.IsNullOrEmpty(_userService.GetUsersByEmp(req.EmployeeNumber).EmployeeNumber))
            {
                return ResultHelper.Error(500, "The EmployeeNumber already exists!");
            }
            //新增用户
            if (_userService.AddUser(req))
            {
                //新增角色
                return ResultHelper.Success("Add Success!");
            }
            return ResultHelper.Error(500, "Add Failure");

        }
        [HttpPost]
        public ApiResponseData UpdateUserData(UserEdit req)
        {

            if (_userService.Update(req))
            {
                if (_roleService.UpdateUserRole(req.Id, req.RoleIds))
                    return ResultHelper.Success("UpdateRole Success!");
            }
            return ResultHelper.Error(500, "UpdateRole Failure");

        }

        [HttpPost]
        public ApiResponseData DeleteUser(DeleteIntId id)
        {
            if (_userService.DeleteUser(id.id))
            {
                return ResultHelper.Success("Delete Success!");
            }
            return ResultHelper.Error(500, "Delete Failure");
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResponseData BatchDelUser(List<int> ids)
        {
            if (_userService.BatchDel(ids))
            {
                return ResultHelper.Success("", "Delete Success");
            }
            return ResultHelper.Error(500, "Delete Failure");
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResponseData ChangeStatusOrPassword(ResetPwdInput input)
        {
            if (_userService.ResetPwdOrStatus(input))
            {
                return ResultHelper.Success("", "Change Success");
            }
            return ResultHelper.Error(500, "Change Failure");
        }
        /// <summary>
        /// 上传头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResponseData FileupLoad([FromForm] IFormFile file, [FromForm] string? employeeNumber)
        {

            //读取旧的头像删除
            _userService.DeleteHeadPortrait(employeeNumber);
            //存头像
            return _userService.SaveHeadPortrait(new FileupLoadInput()
            {
                file = file,
                employeeNumber = employeeNumber
            });
        }
        [HttpGet]
        public ApiResponseData GetPersonInfo(string employeeNumber)
        {
            UserReq user = _userService.GetUsersByEmp(employeeNumber);
            if (user != null)
            {
                UserRoleRelation relation = _roleService.GetRelationByUserId(user.Id);
                RoleRes role = _roleService.GetRoleById(relation.RoleId);
                return ResultHelper.Success(new
                {
                    id = user.Id,
                    employeeNumber = user.EmployeeNumber,
                    roleName = role == null ? string.Empty: role.RoleName,
                    userName = user.UserName,
                    password = "",
                    phoneNumber = user.PhoneNumber,
                    headPortrait = user.HeadPortrait
                });
            }
            return ResultHelper.Error(500, "Get Failure!");
        }
        /// <summary>
        /// 修改个人信息，修改密码
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResponseData UpdatePersonanlInfo(UpdateUserInformation info)
        {
            try
            {
                //修改密码
                if (!info.oldPassword.IsNullOrEmpty() && !info.newPassword.IsNullOrEmpty())
                {
                    //校验密码正确与否
                    var user = _userService.GetUsersById(info.id);
                    if (user == null || user.Password != info.oldPassword)
                    {
                        return ResultHelper.Error(500, "The old password is incorrect");
                    }
                    _userService.Update(new UserEdit()
                    {
                        Id = info.id,
                        PhoneNumber = info.phoneNumber,
                        Password = info.newPassword,
                        UserName = info.userName
                    });
                }
                else
                {
                    //更改用户信息
                    _userService.Update(new UserEdit()
                    {
                        Id = info.id,
                        PhoneNumber = info.phoneNumber,
                        UserName = info.userName
                    });
                }

                //更改角色信息
                if (info.roleName != null)
                {
                    _roleService.UpdateUserRole(info.id, info.roleName);
                }
            }
            catch (Exception ex)
            {
                return ResultHelper.Error(500, "Operate Failure!");
            }
            return ResultHelper.Error(200, "Operate Success!");

        }
    }
}
